<template>
  <div id="app">
    <b-container>
    <h2>A todo list
      <b-badge>@Me</b-badge>
    </h2>
    <b-row>
      <b-col cols="9">
        <b-form-input v-model="text"
                      type="text"
                      placeholder="Enter your text"
                      @keyup.enter="handleEnter"></b-form-input>
      </b-col>
      <b-col cols="1">
        <b-button @click="handleEnter">添加</b-button>
      </b-col>
    </b-row>
    <b-list-group>
      <b-list-group-item v-for="event in events"
                         :id="events.indexOf(event)"
                         :key="events.indexOf(event)">
      <b-row>
        <b-col cols="6">

            <b-form-checkbox
              v-model="event.isDone"
              value="accepted">
              <span v-bind:class="{done:event.isDone=='accepted'}">{{event.text}}</span>

            </b-form-checkbox>

        </b-col>
        <b-col offset="4">
          <b-button variant="danger" @click="handleDelete(events.indexOf(event))">删除</b-button>
        </b-col>
      </b-row>
      </b-list-group-item>
    </b-list-group>
    </b-container>
  </div>
</template>

<script>
  export default {
    name: 'app',
    data() {
      return {
        text: '',
        events: JSON.parse(window.localStorage.getItem('events'))//events的item包含isDone和text
      }
    },
    methods: {
      handleEnter() {
        if (this.text == '')
          return;
        this.events.push({text: this.text, isDone: false});
        this.text = '';
      },
      handleDelete(e){
        console.log(e);
        for(let i=e;i<this.events.length;i++){
          this.events[i]=this.events[i+1];
          this.$set(this.events,i,this.events[i]);
        }
        this.events.length--;
        window.localStorage.setItem('events', JSON.stringify(this.events));
      }
    },
    watch: {
      events: {
        deep: true,
        handler: function () {
          window.localStorage.setItem('events', JSON.stringify(this.events));
        }
      }
    }
  }
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;

    position: absolute;
    left: 0px;
    right: 0px;
    margin-left: 30px;
    margin-right: 30px;
    margin-top: 30px;
  }

  .done {
    text-decoration: line-through;
  }
</style>
